package com.shujia.spark.core

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

import scala.util.Random

object Demo14PI {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setMaster("local[8]")
    conf.setAppName("pi")
    val sc = new SparkContext(conf)

    //构建一个很大的RDD
    val data: RDD[Int] = sc.parallelize(0 until 10000)

    val points: RDD[(Double, Double)] = data
      .map(i => {
        //随机生成正方形内内点
        val x: Double = Random.nextDouble() * 2 - 1
        val y: Double = Random.nextDouble() * 2 - 1
        (x, y)
      })

    //取出园内的点
    val yuan: RDD[(Double, Double)] = points.filter { case (x, y) => x * x + y * y <= 1 }

    //计算圆周率
    val pi: Double = yuan.count().toDouble / points.count() * 4.0

    println(pi)
  }
}
